using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using CodeFactory.IDAL;

namespace CodeFactory.Library.Config
{
    public static class DatabaseManager
    {
        private static string configFile;

        private static List<DatabaseInfo> databaseList;

        private static object lockObj = new object();

        static DatabaseManager()
        {
            databaseList = new List<DatabaseInfo>();
            configFile = string.Format("{0}\\Database.config", System.Environment.CurrentDirectory);
            try
            {
                lock (lockObj)
                {
                    StreamReader sr = new StreamReader(configFile);
                    XmlSerializer xs = new XmlSerializer(typeof(List<DatabaseInfo>));
                    databaseList = xs.Deserialize(sr) as List<DatabaseInfo>;
                    sr.Close();
                }
                if (databaseList == null)
                {
                    LibraryMessageBox.ShowErrorAndExit("DatabaseManager Initialization Error", "Can't load database list from " + configFile);
                }
            }
            catch (Exception e)
            {
                LibraryMessageBox.ShowErrorAndExit("DatabaseManager Initialization Error", e.Message);
            }
        }

        public static void AddDatabase(DatabaseInfo info)
        {
            databaseList.Add(info);
            lock (lockObj)
            {
                StreamWriter sr = new StreamWriter(configFile);
                XmlSerializer xs = new XmlSerializer(typeof(List<DatabaseInfo>));
                xs.Serialize(sr, databaseList);
                sr.Close();
            }
        }

        public static List<DatabaseInfo> DatabaseList
        {
            get { return databaseList; }
        }

        public static IProvider GetDataProvider(DatabaseInfo info)
        {
            lock (lockObj)
            {
                object obj = Assembly.Load(info.DllName).CreateInstance(info.ClassName);
                if (obj == null)
                    throw new Exception(Language.LanguageManager.StringManager["Error_LoadDataLibrary"]);
                else
                    return (IProvider)obj;
            }
        }
    }
}
